<?php

menu_register(array(
	'oauth' => array(
		'callback' => 'user_oauth',
		'hidden' => 'true',
	),
	'reg' => array(
		'callback' => 'user_reg',
		'hidden' => 'true',
	),
	'image' => array(
		'callback' => 'user_image',
		'hidden' => 'true',
	),
	'rookie' => array(
		'callback' => 'user_rookie',
		'hidden' => 'true',
	),
));

function user_image() {
	require_once 'reg.php';
	header('Content-Type: image/jpeg');
	echo req('https://api-secure.recaptcha.net/image?c='.$_GET['c']);
}

function user_reg() {
	require_once 'reg.php';
	if ($_SERVER['REQUEST_METHOD'] == 'GET') {
		if (user_is_authenticated()) {
			header('Location: '. BASE_URL);
		}
		theme('page', __('Registration'), get_reg_content());
	} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
		$error_msg = false;
		$fields = array( 'name', 'screen_name', 'user_password', 'email' );
		foreach ($fields as $field) {
			if (!strcmp($_POST['user'][$field], '')) {
				$error_msg = '所有选项均为必填。';
				break;
			}
		}
		if (!$error_msg && strlen($_POST['user']['user_password']) < 6) {
			$error_msg = '密码长度不够。';
		}

		if (!$error_msg) {
			$r = req('https://twitter.com/account/create', @file_get_contents('php://input'), false);    
			$err_msg = array(
				'You can\'t do that right now.' => '出现未知错误。',
				'Please try to match the 2 words shown above' => '验证码输入错误。',
				'has already been taken' => '用户名或邮箱已有人使用。',
				'is not a valid email address' => '邮箱格式不正确。'
			);
			foreach ($err_msg as $k => $v) {
				if (strpos($r, $k) !== false) {
					$error_msg = $v;
					break;
				}
			}
		}
		if (!$error_msg) {
		  $GLOBALS['user']['username'] = trim($_POST['user']['screen_name']);
		  $GLOBALS['user']['password'] = $_POST['user']['user_password'];
		  $GLOBALS['user']['type'] = 'normal';
		  _user_save_cookie(true);
		  header('Location: '.BASE_URL.'rookie');
		  exit();
		} else {
			$content = '<p>'.$error_msg.'</p><p>请返回<a href="'.BASE_URL.'reg">注册页面</a>重试。';
			theme('page', __('Registration'), $content);
		}
	}
}

function user_rookie() {
	$content = '<p>恭喜你，你的帐号已经注册成功！在正式开始使用之前，有一些内容你应该了解：</p>
	<ul><li>奶瓶腿是一个安全的、个性的中文 Twitter 手机客户端，基于 <a href="http://dabr.co.uk/">Dabr</a> ，由奶瓶 <a href="'.BASE_URL.'user/netputer">@NetPuter</a> 修改/架设，更多介绍请围观 <a href="'.BASE_URL.'about">'.__("About").'</a> 页面。</li>
	<li>想修改资料？在个人页面中点击 <strong><a href="'.BASE_URL.'profile">'.__("Update Profile").'</a></strong> 即可完成。</li>
	<li>推荐关注 <strong><a href="'.BASE_URL.'user/rtmeme">@rtmeme</a></strong> - 一个优秀的机器人，捕捉中文 Twitter 圈最热消息。</li>
	<li>推荐关注 <strong><a href="'.BASE_URL.'user/tuite_tips">@tuite_tips</a></strong> - 中文推特技巧，包括使用技巧，观点评论，各平台客户端介绍， Web 应用介绍，美化，周边商品和线下聚会等。</li>
	<li>推荐关注 <strong><a href="'.BASE_URL.'user/tui3rd">@tui3rd</a></strong> - 推特第三方，关注推友自行开发/修改/维护的第三方 Twitter 客户端。</li>
	<li>推荐使用 <strong><a href="https://zdx.in/">Rabr</a></strong> ，基于 Twitese 推特中文圈修改、优化、美化，适合在电脑上使用。</li>
	<li>……</li>
	</ul><p />我知道了，现在就<a href="'.BASE_URL.'">开始 Twitter 之旅</a>吧！';
	theme('page', __('To Rookies'), $content);
}

function user_oauth() {
	// Session used to keep track of secret token during authorisation step
	session_start();
	// Flag forces twitter_process() to use OAuth signing
	$GLOBALS['user']['type'] = 'oauth';
	if ($oauth_token = $_GET['oauth_token']) {
		// Generate ACCESS token request
		$params = array('oauth_verifier' => $_GET['oauth_verifier']);
		$response = twitter_process(OAUTH_URL.'access_token', $params);
		parse_str($response, $token);
		// Store ACCESS tokens in COOKIE
		$GLOBALS['user']['password'] = $token['oauth_token'] .'|'.$token['oauth_token_secret'];
		// Fetch the user's screen name with a quick API call
		unset($_SESSION['oauth_request_token_secret']);
		$user = twitter_process(NETPUTWEETS_API.'account/verify_credentials.json');
		$GLOBALS['user']['username'] = $user->screen_name;
		_user_save_cookie(1);
		header('Location: '. BASE_URL);
		exit();
	} else {
		// Generate AUTH token request
		$params = array('oauth_callback' => BASE_URL.'oauth');
		$response = twitter_process(OAUTH_URL.'request_token', $params);
		parse_str($response, $token);
		// Save secret token to session to validate the result that comes back from Twitter
		$_SESSION['oauth_request_token_secret'] = $token['oauth_token_secret'];
		// redirect user to authorisation URL
		$authorise_url = ITAP_URL.'authorize?oauth_token='.$token['oauth_token'];
		header("Location: $authorise_url");
	}
}

function user_oauth_sign(&$url, &$args/* = false*/) {
    require_once 'lib_oauth.php';
	$method = $args !== false ? 'POST' : 'GET';
	// Move GET parameters out of $url and into $args
	if (preg_match_all('#[?&]([^=]+)=([^&]+)#', $url, $matches, PREG_SET_ORDER)) {
		foreach ($matches as $match) {
			$args[$match[1]] = $match[2];
		}
	    $url = substr($url, 0, strpos($url, '?'));
    }
 
	if (($oauth_token = $_GET['oauth_token']) && $_SESSION['oauth_request_token_secret']) {
		$oauth_token_secret = $_SESSION['oauth_request_token_secret'];
	} else {
		list($oauth_token, $oauth_token_secret) = explode('|', $GLOBALS['user']['password']);
    }

    	$keys = array(
	        'oauth_key'		=> OAUTH_CONSUMER_KEY,
            'oauth_secret'	=> OAUTH_CONSUMER_SECRET,
            'user_key'      => $oauth_token,
            'user_secret'   => $oauth_token_secret,
        );
    if ($method == 'POST') {
        $kw = array();
        foreach ($args as $k => $v) {
            $v = str_replace("~", "～", $v);
            $kw[$k] = $v;
        }
    }
    $url = oauth_sign_get($keys, $url, $kw, $method);

    if ($method == 'POST'){
        list($url, $args) = explode('?', $url, 2);
    }else{
        $args = false;
    }
}

function user_ensure_authenticated() {
	if (!user_is_authenticated()) {
		$content = theme('login');
		theme('page', __("Login"), $content);
	}
}

function user_logout() {
	unset($GLOBALS['user']);
	setcookie('USER_AUTH', '', time() - 3600, WEB_ROOT);
}

function user_is_authenticated() {
	if (!isset($GLOBALS['user'])) {
		if(array_key_exists('USER_AUTH', $_COOKIE)) {
			_user_decrypt_cookie($_COOKIE['USER_AUTH']);
		} else {
			$GLOBALS['user'] = array();
		}
	}
	
	if (!$GLOBALS['user']['username']) {
		if ($_POST['username'] && $_POST['password']) {
			if($_POST['stay-logged-in']=='yes'){
				//try to use oauth
				//require_once 'OAuth.php';
				$GLOBALS['user']['type'] = 'oauth';
				session_start();
				$params = array('oauth_callback' => BASE_URL.'oauth');
                $response = twitter_process(OAUTH_URL.'request_token', $params);
                parse_str($response, $token);

				// Save secret token to session to validate the result that comes back from Twitter
				$_SESSION['oauth_request_token_secret'] = $token['oauth_token_secret'];

				// redirect user to authorisation URL
				$authorise_url = OAUTH_URL.'authorize?oauth_token='.$token['oauth_token'];
				//header("Location: $authorise_url");
				$str = file_get_contents($authorise_url);
				$authenticity_pattern = '/.*input name="authenticity_token" type="hidden" value="([a-z0-9]*)".*/';
				preg_match($authenticity_pattern,$str,$matches);
				$postdata = "authenticity_token=".$matches[1];
				$oauth_token_pattern = '/input id="oauth_token" name="oauth_token" type="hidden" value="([A-Za-z0-9]*)".*/';
				preg_match($oauth_token_pattern,$str,$matches);
				$postdata .= "&oauth_token=".$matches[1];
				$postdata .= "&session[username_or_email]=".$_POST['username']."&session[password]=".$_POST['password']."&submit=Allow";
				$url = OAUTH_URL."authorize";
				$ch = curl_init($url);
				curl_setopt($ch,CURLOPT_POST,TRUE);
				curl_setopt($ch,CURLOPT_POSTFIELDS,$postdata);
				curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
				$str = curl_exec($ch);
				curl_close($ch);
				$redirect_url_pattern = '/<a href="([^"]*)">click here<\/a>/';
				preg_match($redirect_url_pattern,$str,$matches);
				if (!empty($matches[1])) {
					$url = str_replace("&amp;","&",$matches[1]);
					header("Location: ".$url);
					exit();
				}
				//end of try to oauth
            }
            $GLOBALS['user']['username'] = trim($_POST['username']);
			$GLOBALS['user']['password'] = $_POST['password'];
			$GLOBALS['user']['type'] = 'normal';
			_user_save_cookie($_POST['stay-logged-in'] == 'yes');
			header('Location: '. BASE_URL);
			exit();
		} else {
			return false;
		}
	}
	return true;
}

function user_current_username() {
	return $GLOBALS['user']['username'];
}

function user_is_current_user($username) {
	return (strcasecmp($username, user_current_username()) == 0);	
}

function user_type() {
	return $GLOBALS['user']['type'];
}

function _user_save_cookie($stay_logged_in = 0) {
	$cookie = _user_encrypt_cookie();
	$duration = 0;
	if ($stay_logged_in) {
		$duration = time() + (3600 * 24 * 365);
	}
	setcookie('USER_AUTH', $cookie, $duration, WEB_ROOT);
}

function _user_encryption_key() {
	return ENCRYPTION_KEY;
}

function _user_encrypt_cookie() {
	$plain_text = $GLOBALS['user']['username'] . ':' . $GLOBALS['user']['password'] . ':' . $GLOBALS['user']['type'];
	if (function_exists('mcrypt_module_open')) {
		$td = mcrypt_module_open('blowfish', '', 'cfb', '');
		$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
		mcrypt_generic_init($td, _user_encryption_key(), $iv);
		$crypt_text = mcrypt_generic($td, $plain_text);
		mcrypt_generic_deinit($td);
		return base64_encode($iv.$crypt_text);
	} else {
		$crypt_text = xxtea_encrypt($plain_text,_user_encryption_key());
		return base64_encode($crypt_text);
	}
}
	
function _user_decrypt_cookie($crypt_text) {
	$crypt_text = base64_decode($crypt_text);
	if(function_exists('mcrypt_module_open')) {
		$td = mcrypt_module_open('blowfish', '', 'cfb', '');
		$ivsize = mcrypt_enc_get_iv_size($td);
		$iv = substr($crypt_text, 0, $ivsize);
		$crypt_text = substr($crypt_text, $ivsize);
		mcrypt_generic_init($td, _user_encryption_key(), $iv);
		$plain_text = mdecrypt_generic($td, $crypt_text);
		mcrypt_generic_deinit($td);
	} else {
		$plain_text = xxtea_decrypt($crypt_text,_user_encryption_key());
	}
	list($GLOBALS['user']['username'], $GLOBALS['user']['password'], $GLOBALS['user']['type']) = explode(':', $plain_text);
}

function theme_login() {
	$content = '<p><b>[1] <a href="'.BASE_URL.'oauth">'.__("Sign In with Twitter/OAuth").'</a></b> (from 奶瓶腿)</p><p><b>[2] '.__("Enter your Twitter Username and Password below").'</b> (from Dabr)<form method="post" action="'.$_GET['q'].'">'.__("Username").' <input name="username" size="15"><br />'.__("Password").' <input name="password" type="password" size="15"><br /><input type="submit" value="'.__("Sign In").'"><label><input type="checkbox" value="yes" checked="check" name="stay-logged-in"> '.__("Remember Me?").' </label></form></p>';
	if (REG == 1) $content .= '<p><b>[3] <a href="'.BASE_URL.'reg">'.__("Sign Up Now").'</a></b></p>';
	return $content;
}

function theme_logged_out() {
	return '<p>'.__("Logged out").'. <a href="'.BASE_URL.'">'.__("Login again").'?</a></p>';
}

?>
